<?php
//----------------------------------------------------------------------------------------
//                            _ooOoo_                                                    |
//                           o8888888o                                                   |
//                           88" . "88                                                   |
//                           (| -_- |)                                                   |
//                            O\ = /O                                                    |
//                        ____/`---'\___                                                 |
//                       .   ' \\| |// `.                                                |
//                        / \\||| : |||// \                                              |
//                       / _||||| -:- |||||- \                                           |
//                         | | \\\ - /// | |                                             |
//                        | \_| ''\---/'' | |                                            |
//                        \ .-\__ `-` ___/-. /                                           |
//                      ___`. .' /--.--\ `. . __                                         |
//                   ."" '< `.___\_<|>_/___.' >'"".                                      |
//                  | | : `- \`.;`\ _ /`;.`/ - ` : | |                                   |
//                  \ \ `-. \_ __\ /__ _/ .-` / /                                        |
//          ======`-.____`-.___\_____/___.-`____.-'======                                |
//                              `=---='                                                  |
//                                                                                       |
//          .............................................                                |
//              佛祖镇楼                 BUG莫侵                                           |
//-----------------------------------------------------------------------------------------
namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\ShopDish;
use App\Models\ShopDishAttribute;
use App\Models\ShopMenu;
use App\Repositories\ShopClerkRepository;
use App\Tools\Map;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Shop;
use App\Models\Order;
use App\Models\ShopInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
Class ShopDishController extends Controller
{

    /**
     *  上传菜式图片   eg 西红柿炒蛋
     * @param Request $request
     */
    public function upload(Request $request){
        if($_FILES['thumb']['size'] == 0 || $_FILES['thumb']['size']>1024*1024) {
            return show(201, '请上传1M以内的图片');
        }
        $rules = [
            'shop_id'=>'required|integer|exists:shops,id',
            'thumb'=>'required|image'
        ];
        $message = [
            'shop_id.*' =>'商家不存在',
            'thumb.*' => '请上传图片'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $type = $request->file('thumb')->getClientOriginalExtension();
        if (!in_array($type,['jpg','jpeg','png'])){
            return show(201,'请上传png|jpg|jpeg格式的图片');
        }
        $user_id = Auth::id();
        if (!Shop::checkIsShop($request->shop_id,$user_id)){
            return show(203,'用户暂无该商家');
        }
        $path = $request->file('thumb')->storePublicly('shop_'.$request->shop_id.'/cuisine');
        return show(200,'上传成功','/storage/'. $path);
    }

    public function showAllDishes(Request $request){
        // 验证
        $rules = [
            'shop_id'=>'required|integer|exists:shops,id',
        ];
        $message = [
            'shop_id.*'=> '商家不存在'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
//        $user_id = Auth::id();
//        if (!Shop::checkIsShop($request->shop_id,$user_id)){
//            return show(203,'用户暂无该商家');
//        }
        // 逻辑处理
        //获取相应的菜式
        $dishes = ShopDish::where('shop_id',$request->shop_id)->get()->toArray();

        //判断多规格
        foreach($dishes as $k=>$v){
//            if (strpos($v['thumb'],';')){
//                $res = explode(';',$v['thumb']);
//                $dishes[$k]['thumb']=$res[0];
//            }
            if($v['is_attr']==1){
                $dishes[$k]['attribute'] = ShopDishAttribute::where('dish_id',$v['id'])->get();
                //处理多规格
                for($y=0;$y<count($dishes[$k]['attribute']);$y++)
                {
                    $spec=explode(",", $dishes[$k]['attribute'][$y]['spec']);
                    foreach($spec as $k2=>$v2)
                    {
                        $spec[$k2] = explode("|",$v2);
                        $specend[$k2]['spec_name'] = $spec[$k2][0];
                        $specend[$k2]['spec_price'] = $spec[$k2][1];
                    }
                    $dishes[$k]['attribute'][$y]['spec']=$specend;
                }
            }
        }
        return show(200,'所有菜式信息获取成功',$dishes);
    }
    /**
     *  根据商家ID获取该商家所有的菜式
     * @param Request $request
     * @return array
     */
    public function showAllDesignDishes(Request $request){
        // 验证
        $rules = [
            'shop_id'=>'required|integer|exists:shops,id',
        ];
        $message = [
            'shop_id.*'=> '商家不存在'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $user_id = Auth::id();
        if (!Shop::checkIsShop($request->shop_id,$user_id)){
            return show(203,'用户暂无该商家');
        }
        // 逻辑处理
        //获取相应的菜式
        $dishes = ShopDish::where('shop_id',$request->shop_id)->get(['id','dishes_name','status','thumb','price','shop_id'])->toArray();

        //判断多规格
        foreach($dishes as $k=>$v){
            if (strpos($v['thumb'],';')){
                $res = explode(';',$v['thumb']);
                $dishes[$k]['thumb']=$res[0];
            }
          /*  if($v['is_attr']==1){
                $dishes[$k]['attribute'] = ShopDishAttribute::where('dish_id',$v['id'])->get();
                //处理多规格
                for($y=0;$y<count($dishes[$k]['attribute']);$y++)
                {
                    $spec=explode(",", $dishes[$k]['attribute'][$y]['spec']);
                    foreach($spec as $k2=>$v2)
                    {
                        $spec[$k2] = explode("|",$v2);
                        $specend[$k2]['spec_name'] = $spec[$k2][0];
                        $specend[$k2]['spec_price'] = $spec[$k2][1];
                    }
                    $dishes[$k]['attribute'][$y]['spec']=$specend;
                }
            }*/
        }
        return show(200,'所有菜式信息获取成功',$dishes);
    }
    // 根据ID获取菜单分类
    public function  showOneDish(Request $request){
        $rules = [
            'id'=>'required|integer|exists:shop_dishes,id',
            'shop_id'=>'required|integer|exists:shops,id',
        ];
        $message = [
            'id.*'=> '菜式不存在',
            'shop_id.*'=> '商家不存在'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        try{
            $dish = ShopDish::where('shop_id',$request->shop_id)->where('status',1)->find($request->id);
            if($dish){
                $dish = $dish->toArray();
            }else{
                return show(202,'暂无该菜式');
            }

            if ($dish['is_attr'] == 1){
                $dish['attribute'] = ShopDishAttribute::where('dish_id',$request->id)->get();
                //处理多规格
                for($y=0;$y<count($dish['attribute']);$y++)
                {
                    $spec=explode(",", $dish['attribute'][$y]['spec']);
                    foreach($spec as $k2=>$v2)
                    {
                        $spec[$k2] = explode("|",$v2);
                        $specend[$k2]['spec_name'] = $spec[$k2][0];
                        $specend[$k2]['spec_price'] = $spec[$k2][1];
                    }
                    $dish['attribute'][$y]['spec']=$specend;
                    $dish['attribute'][$y]['attr_id']=$dish['attribute'][$y]['id'];
                }
            }
        }catch (\Exception $e){

        }

        return show(200,'菜式信息获取成功',$dish);
    }
    // 添加菜式
    public function addDish(Request $request){
        $rules = [
            'dishes_name'=>'required|string',
            'shop_id'=>'required|integer|exists:shops,id',
            'menu_id' => 'required|integer|exists:shop_menu,id',
            'price' => 'required',
            'discount'=>'required|numeric|between:0,1',
            'thumb'=>'required|string',
            'is_attr'=>'required|in:0,1',
            'spec_arr' =>'array',
            'description'=>'string|min:3|max:100'
        ];
        $message = [
            'shop_id.*' =>'商家不存在',
            'menu_id.*' => '菜式分类不正确',
            'price.*' =>'菜式价格有误',
            'discount.*' =>'折扣有误',
            'thumb.*' =>'请上传图片',
            'is_attr.*'=>'多规格参数有误',
            'spec_arr.*'=>'多规格参数错误',
            'dishes_name.*'=>'名称有误',
            'description.string'=>'请填写菜式介绍',
            'description.min'=>'菜式介绍太长了',
            'description.max'=>'菜式介绍太长了'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
//        $user_id = Auth::id();
//        if (!Shop::checkIsShop($request->shop_id,$user_id)){
//            return show(203,'用户暂无该商家');
//        }
        $res = ShopMenu::where('shop_id',$request->shop_id)->where('id',$request->menu_id)->get();
        if (count($res)<1){
            return show(204,'商家暂无该分类');
        }
        $discount = doubleval($request->discount);
        $price = doubleval($request->price);
        $discount_price = $discount*$price;
        $created_at = date("Y-m-d H:i:s");
        $updated_at = date("Y-m-d H:i:s");
        $data = array_merge(
            \request(['shop_id','menu_id','dishes_name','thumb','is_attr','description']),
            compact('discount_price','price','discount','created_at','updated_at')
        );
        DB::beginTransaction();
        try{
             // 创建菜式
            $dish_id = DB::table('shop_dishes')->insertGetId($data);
            // @todo 多规格处理
            if ($request->is_attr == 1) {

                $spec_arr = $request->spec_arr;
                $designArr = [];
                for ($i=0;$i<count($spec_arr);$i++){
                    $designArr[$i]['dish_id']= $dish_id;
                    $designArr[$i]['attribute']= $spec_arr[$i]['attribute'];
                    $designArr[$i]['spec']= $spec_arr[$i]['spec'];
                    $designArr[$i]['created_at']= date("Y-m-d H:i:s");
                    $designArr[$i]['updated_at']= date("Y-m-d H:i:s");
                }
                DB::table('shop_dish_attribute')->insert($designArr);

            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
//            dd($e->getMessage());
            return show(202,'添加菜式失败');
        }
        return show(200,'添加菜式成功');
    }


    // 编辑菜单分类
    public function editDish(Request $request){
        $rules = [
            'shop_id'=>'required|integer|exists:shops,id',
            'menu_id' => 'required|integer|exists:shop_menu,id',
            'id' => 'required|integer|exists:shop_dishes,id',
            'dishes_name'=>'required|string',
            'price' => 'required|numeric|min:0',
            'discount'=>'required|numeric|between:0,1',
            'thumb'=>'string',
            'is_attr'=>'required|in:0,1',
            'spec_arr' =>'array',
            'description'=>'string|min:3|max:100'
        ];
        $message = [
            'shop_id.*' =>'商家不存在',
            'menu_id.*' => '菜式分类不存在',
            'id.*' => '菜式不存在',
            'price.*'=>'菜式价格有误',
            'discount.*' =>'折扣有误',
            'thumb.*' =>'请上传图片',
            'is_attr.*'=>'请选择是否多规格',
            'spec_arr.*'=>'多规格参数错误',
            'dishes_name.*'=>'菜式名称有误',
            'description.string'=>'请填写菜式介绍',
            'description.min'=>'菜式介绍太长了',
            'description.max'=>'菜式介绍太长了'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $user_id = Auth::id();
        if (!Shop::checkIsShop($request->shop_id,$user_id)){
            return show(203,'用户暂无该商家');
        }
        $discount = doubleval($request->discount);
        $price = doubleval($request->price);
        $discount_price = $discount*$price;
        $data = array_merge(
            \request(['menu_id','dishes_name','thumb','is_attr','description']),
//            ['menu_id','dishes_name','description','price','discount','thumb','is_attr'],
            compact('discount_price','price','discount')
        );
        DB::beginTransaction();
        try{
            DB::table('shop_dishes')
                ->where('id',$request->id)
                ->update($data);
            // @todo 多规格处理
            if ($request->is_attr == 1) {
                $spec_arr = $request->spec_arr;

                $designArr = [];
                $res = DB::table('shop_dish_attribute')->where('dish_id',$request->id)->where('deleted_at','=',null)->get(['id']);

                if($res->isEmpty()){    // 新增
                    for ($i=0;$i<count($spec_arr);$i++){
                        $designArr[$i]['dish_id']= $request->id;
                        $designArr[$i]['attribute']= $spec_arr[$i]['attribute'];
                        $designArr[$i]['spec']= $spec_arr[$i]['spec'];
                        $designArr[$i]['created_at']= date("Y-m-d H:i:s");
                        $designArr[$i]['updated_at']= date("Y-m-d H:i:s");
                    }
                    DB::table('shop_dish_attribute')->insert($designArr);
                }else{
                    foreach ($res as $k=>$v){
                        $dish_attr_ids[]= $v->id;
                    }
                    foreach ($spec_arr as $kk=>$vv){
                        if ($vv['attr_id'] == '-1'){
                            $msData['attribute'] = $vv['attribute'];
                            $msData['spec'] = $vv['spec'];
                            $msData['dish_id'] = $request->id;
                            $msData['created_at'] = date("Y-m-d H:i:s");
                            $msData['updated_at'] = date("Y-m-d H:i:s");
                            $nid = DB::table('shop_dish_attribute')->where('dish_id',$request->id)->insertGetId($msData);
                            $dish_attr_ids_rm[]= $nid;
                            unset($msData);
                            break;
                        }else{
                           if (in_array($vv['attr_id'],$dish_attr_ids)){
                                $msData['attribute'] = $vv['attribute'];
                                $msData['spec'] = $vv['spec'];
                                $msData['updated_at'] = date("Y-m-d H:i:s");
                                DB::table('shop_dish_attribute')->where('id', $vv['attr_id'])->update($msData);
                                unset($msData);
                                $dish_attr_ids_rm[]= $vv['attr_id'];
                            }
                        }
                    }
                    // 统一处理
                    DB::table('shop_dish_attribute')->where('dish_id',$request->id)->whereNotIn('id',$dish_attr_ids_rm)->update(['deleted_at'=>date('Y-m-d H:i:s'),'status'=>0]);
                }
            }else{
                DB::table('shop_dish_attribute')->where('dish_id',$request->id)->update(['deleted_at'=>date('Y-m-d H:i:s'),'status'=>0]);
            }
            DB::commit();
            return show(200,'修改成功');
        }catch (\Exception $e){
            DB::rollBack();
            dd($e->getMessage());
            return show(202,'修改失败');
        }
    }

    public function showDesignDish(Request $request){
        $rules = [
            'id'=>'required|integer|exists:shop_dishes,id',
            'shop_id'=>'required|integer|exists:shops,id',
        ];
        $message = [
            'id.*'=> '菜式不存在',
            'shop_id.*'=> '商家不存在'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        try{
            $shop = Shop::where('is_check',1)->select('id','shop_name','note','latitude','longitude','shop_pic')->find($request->shop_id);
            $shopinfo = ShopInfo::where('shop_id',$request->shop_id)->first();
            if (!$shop){
                return show(203,'该商家未审核通过');
            }
            $shopinfo = $shopinfo->toArray();
            $shop = $shop->toArray();
            $collection = collect([$shop,$shopinfo]);
            $collapsed = $collection->collapse();
            $myshop = $collapsed->all();
            $dish = ShopDish::where('shop_id',$request->shop_id)->find($request->id);
            if($dish){
                $dish = $dish->toArray();
            }else{
                return show(202,'暂无该菜式');
            }

            if ($dish['is_attr'] == 1){
                $dish['attribute'] = ShopDishAttribute::where('dish_id',$request->id)->get();
                //处理多规格
                for($y=0;$y<count($dish['attribute']);$y++)
                {
                    $spec=explode(",", $dish['attribute'][$y]['spec']);
                    foreach($spec as $k2=>$v2)
                    {
                        $spec[$k2] = explode("|",$v2);
                        $specend[$k2]['spec_name'] = $spec[$k2][0];
                        $specend[$k2]['spec_price'] = $spec[$k2][1];
                    }
                    $dish['attribute'][$y]['spec']=$specend;
                }
            }
            $comments = Comment::with(['users'=>function($query){
                $query->select('id','name','avatar');
            }])->where('shop_id',$request->shop_id)->orderBy('created_at','desc')->limit(10)->get(['id','content','score','thumb','created_at','user_id']);
        }catch (\Exception $e){
            dd($e->getMessage());
            return show(202,'暂无该菜式');
        }

        return show(200,'信息获取成功',['shop'=>$myshop,'dish'=>$dish,'comments'=>$comments]);
    }

    // 菜式删除
    public function dishDelete(Request $request){

        try{
            $rules = [
                'id'=>'required|integer|exists:shop_dishes,id',
            ];
            $message = [
                'id.*'=> '菜式不存在',
            ];
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(201,$validator->errors()->first());
            }
            $dish_id = $request->id;
            $dish = ShopDish::where('id',$dish_id)->first();
            if (!$dish){
                return show(202,'删除失败');
            }
            DB::beginTransaction();
            $res1 = ShopDish::where('id',$dish_id)->delete();
            $attrs = ShopDishAttribute::where('dish_id',$dish_id)->get();
            if ($attrs->isEmpty()){
                DB::commit();
                return show(200,'删除成功');
            }else{
                $res2 = ShopDishAttribute::where('dish_id',$dish_id)->delete();
                if ($res1 && $res2){
                    DB::commit();
                    return show(200,'删除成功');
                }else{
                    DB::rollBack();
                    return show(202,'删除失败');
                }
            }
        }catch (\Exception $e){
            DB::rollBack();
            return show(202,'删除失败');
        }
    }
    // 菜式的上下架
    public function  dishStatus(Request $request){
        try{
            $rules = [
                'id'=>'required|integer|exists:shop_dishes,id',
                'status'=>'required|in:0,1'
            ];
            $message = [
                'id.*'=> '菜式不存在',
                'status.*'=>'商品状态不合法'
            ];
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(201,$validator->errors()->first());
            }
            $dish_id = $request->id;
            $status = $request->status;
            $dish = ShopDish::where('id',$dish_id)->first();
            if (!$dish){
                return show(201,'更新失败');
            }
            $result = ShopDish::where('id',$dish_id)->update(['status'=>$status]);
            if ($result){
                return show(200,'更新成功');
            }else{
                return show(202,'更新失败');
            }
        }catch (\Exception $e){
            return show(202,'更新失败');
        }

    }
}